package com.jcl.recruit.wechat.service;

import com.jcl.core.security.ShareUserToken;
import com.jcl.core.utils.CollectionUtils;
import com.jcl.core.utils.HttpRequest;
import com.jcl.recruit.attach.vo.AttachmentPhotoVo;
import com.jcl.recruit.core.constants.Constants;
import com.jcl.recruit.core.constants.UserExternalLoginConstant;
import com.jcl.recruit.login.service.UserExternalAccessLogin;
import com.jcl.recruit.login.service.impl.LoginServiceImpl;
import com.jcl.recruit.login.vo.UserExternalLoginInfo;
import com.jcl.recruit.user.logic.UserExternalAccessLogic;
import com.jcl.recruit.user.logic.UserRegisterLogic;
import com.jcl.recruit.user.model.User;
import com.jcl.recruit.user.model.UserExternalAccess;
import com.jcl.recruit.wechat.logic.WechatCommonLogic;
import com.jcl.recruit.wechat.utils.WechatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Service
public class WechatLoginService extends LoginServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(WechatLoginService.class);

    @Autowired
    private UserExternalAccessLogin userExternalAccessLogin;

    @Autowired
    private UserExternalAccessLogic userExternalAccessLogic;

    @Autowired
    private WechatCommonLogic wechatCommonLogic;

    @Autowired
    private UserRegisterLogic userRegisterLogic;

    /* *
     * @Author yyliu
     * @Description //TODO
     * @Date 10:21 2018/10/19
     * @Param [userInfo]
     * @return com.example.service.login.entity.UserExternalLoginInfo
     **/
    public UserExternalLoginInfo accessLogin(WechatUtils.WechatUserInfo userInfo) {

        // 登录
        UserExternalLoginInfo externalLoginInfo = userExternalAccessLogin.
                loginByExternalKey(userInfo.getOpenid(), UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT);

        if (null == externalLoginInfo) {
            // 用户不存在， 创建用户到 默认企业
            UserExternalAccess userExternalAccess = userExternalAccessLogic.
                    addExternalUserByExternalKey(userInfo.getOpenid(), userInfo.getUnionid(),
                            userInfo.getNickname(),
                            UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT,
                            UserExternalLoginConstant.USER_ACCESS_STATUS_USED);

            User user = new User();
            user.setRealname(userInfo.getNickname());
            try {
                user = userRegisterLogic.tryRegisterUser(user, Constants.SubcompanyInfo.DEFAULT_TRY_CODE,
                        Constants.DepartmentInfo.DEFAULT_TRY_ID);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            userExternalAccess.setCorpCode(user.getCorpCode());
            userExternalAccess.setUserId(user.getId());
            userExternalAccess.setUsername(userExternalAccess.getExternalKey()
                    + UserExternalLoginConstant.USER_ACCESS_SPLIT + user.getCorpCode());
            userExternalAccessLogic.updateAccess(userExternalAccess);

            byte[] b = HttpRequest.getByte(userInfo.getHeadimgurl());
            AttachmentPhotoVo vo = new AttachmentPhotoVo();
            vo.setBytes(b);
            vo.setFileName(userInfo.getOpenid());

            wechatCommonLogic.updateUserHead(vo, user.getId(), user.getCorpCode());

            externalLoginInfo = new UserExternalLoginInfo();

            externalLoginInfo.setUsername(userExternalAccess.getUsername());
            externalLoginInfo.setPassword(userExternalAccess.getPassword());
            externalLoginInfo.setUserId(userExternalAccess.getUserId());
            externalLoginInfo.setCorpCode(userExternalAccess.getCorpCode());
        }

        return externalLoginInfo;
    }

    /* *
     * @Author yyliu
     * @Description 微信邀约登录
     *
     * @Date 9:38 2018/9/14
     * @Param [code]
     * @return com.example.core.wechat.WechatUtils.AccessLoginInfo
     **/
    public WechatUtils.AccessLoginInfo accessLoginByInvite(WechatUtils.WechatUserInfo userInfo,
                                                           String accessKey) {

        WechatUtils.AccessLoginInfo loginInfo = new WechatUtils.AccessLoginInfo();
        // 获取登录的微信用户信息
        ShareUserToken tokenInfo = ShareUserToken.decodeInviteToken(accessKey);
        if (null == tokenInfo) {
            loginInfo.setCode("error");
            loginInfo.setMsg("state param is error !");
            return loginInfo;
        }

        // 邀约人自己 点击
        UserExternalAccess inviter = userExternalAccessLogic.findWechatOneByUserId(
                Integer.valueOf(tokenInfo.getUserId()));
        if (null != inviter) {
            if (inviter.getExternalKey().equals(loginInfo.getOpenId())) {
                loginInfo.setMsg("您好邀约人不能操作！");
                loginInfo.setCode("warning");
                return loginInfo;
            }
        }

        UserExternalAccess userAccess = userExternalAccessLogic.
                findOneByExternalKeyAndCode(userInfo.getOpenid(), tokenInfo.getCorpCode());
        ;
        // 判断用户是否已经注册当前邀约企业
        if (null != userAccess && null != userAccess.getUserId()) {
            // 存在，直接登录

            userExternalAccessLogic.changeUseStatusToUnused(
                    userInfo.getOpenid(), UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT);
            // 默认使用当前企业
            userAccess.setStatus(UserExternalLoginConstant.USER_ACCESS_STATUS_USED);
            userExternalAccessLogic.updateAccess(userAccess);

            User user = userLogic.findOneById(userAccess.getUserId());
            loginInfo.setUser(user);
            loginInfo.setCode("login");
            loginInfo.setUserExternalAccess(userAccess);
            return loginInfo;
        } else {
            List<UserExternalAccess> userAccessList = userExternalAccessLogic.findListByExternalKey(
                    userInfo.getOpenid(), UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT,
                    UserExternalLoginConstant.USER_ACCESS_STATUS_TEMP);

            if (CollectionUtils.isEmpty(userAccessList)) {
                // 用户不存在， 默认使用 临时账户
                userAccess = userExternalAccessLogic.
                        addExternalUserByExternalKey(userInfo.getOpenid(), userInfo.getUnionid(),
                                userInfo.getNickname(),
                                UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT,
                                UserExternalLoginConstant.USER_ACCESS_STATUS_TEMP);
            } else {
                userAccess = userAccessList.get(0);
            }

            loginInfo.setCode("register");
            loginInfo.setUserExternalAccess(userAccess);
            return loginInfo;
        }
    }

    public WechatUtils.WechatUserInfo getWechatUserInfo(String code) {
        // 获取微信登录的token和openId
        WechatUtils.WechatCodeMessage codeMessage = WechatUtils.getCodeObject(code);

        // 获取登录的微信用户信息
        WechatUtils.WechatUserInfo userInfo = WechatUtils.getUserInfoObject(codeMessage.getAccess_token(),
                codeMessage.getOpenid());

        return userInfo;
    }

}
